<?php
/**
 * created by zzy
 * date: 2018/1/11 10:42
 */

namespace App\Http\Admin\Export\Controllers;
use App\Eloquent\Ygt\Process;
use App\Eloquent\Ygt\ProcessField;
use App\Eloquent\Ygt\ProcessFieldCategory;
use App\Eloquent\Ygt\ProcessFieldRelation;
use App\Eloquent\Ygt\ProcessFieldRelationSelect;
use App\Engine\Func;
use Framework\BaseClass\Http\Admin\Controller;

class ProcessController extends Controller
{
    public function index()
    {
        $adminUser          = request()->user('admin')->toArray();
        $companyId          = $adminUser['company_id'];

        $where              = ['company_id'=>$companyId];
        $collection         = Process::getList($where,'','','',['id','desc']);
        $processList        = $collection->toArray();
        $excelData          = [];
        if($processList)
        {
            //厂的工序字典
            //$typeListArr                = ProcessField::getTypeList(1);
            $where                      = ['company_id'=>$companyId];
            $fieldCategoryList          = ProcessFieldCategory::getRows($where);
            $typeListArr                = Func::getIdTitleByType( $fieldCategoryList, 1 );
            $fieldTypeListArr           = ProcessField::getFieldTypeList(1);
            $dictList                   = ProcessField::getCompanyFieldList($companyId);
            $dictListArr                = [];
            foreach($dictList as $key=>$val)
            {
                $valId                  = $val['id'];
                $valType                = $val['type'];
                $valFieldType           = $val['field_type'];
                $arr                    = $val;
                $arr['type_name']        = $typeListArr[$valType];
                $arr['field_type_name'] = $fieldTypeListArr[$valFieldType];
                $dictListArr[$valId]    = $arr;
            }
            //工序关联的字段
            $processListArr             = $processIdArr = [];
            foreach($processList as $key=>$val)
            {
                $valId                  = $val['id'];
                $processIdArr[]         = $valId;
                $processListArr[$valId] = $val;
            }
            $where                      = ['process_id'=>['in',$processIdArr]];
            $relationColletion          = ProcessFieldRelation::getList($where,'','','',['orderby','asc']);
            $relationList               = $relationColletion->toArray();
            $isMustArr                  = [0=>'选填',1=>'必填'];
            $relationListArr            = $relationIdArr = [];
            foreach($relationList as $key=>$val)
            {
                $valId                  = $val['id'];
                $relationIdArr[]        = $valId;
                $relationListArr[$valId]= $val;
            }
            //工序关联的字段的下拉字段
            $where                      = ['relation_id'=>['in',$relationIdArr]];
            $fields                     = 'id,pid,relation_id,title,title_type';
            $selectCollection           = ProcessFieldRelationSelect::getList($where,$fields);
            $selectList                 = $selectCollection->toArray();
            $selectListArr              = [];
            foreach($selectList as $key=>$val)
            {
                $valRelationId          = $val['relation_id'];
                $selectListArr[$valRelationId][]  = $val;
            }
            foreach($relationList as $key=>$val)
            {
                $valId                  = $val['id'];
                $valProcessId           = $val['process_id'];
                $valFieldId             = $val['field_id'];
                $valIsMust              = $val['is_must'];
                if(!isset($dictListArr[$valFieldId])){
                    continue;
                }
                $arr                    = $dictListArr[$valFieldId];
                $arr['relation_id']    = $valId;
                $arr['must_name']      = $isMustArr[$valIsMust];
                $tempData               = [];
                if(isset($selectListArr[$valId])){
                    $tempDataList       = $selectListArr[$valId];
                    $arrFieldType       = $arr['field_type'];
                    $tempData           = Process::setRelationSelectData($tempDataList,$arrFieldType);
                }
                $arr['data']           = $tempData;
                $processListArr[$valProcessId]['data'][]      = $arr;
            }//return $processListArr;exit;
            $excelData      = $this->setData($processListArr);
        }
        return $this->exportExcel($excelData);
    }
    public function setData($data)
    {
        $dataTitle      = ['工序名称','工序字段','字段类型','第一列值','第二列值'];
        $resultData     = $cellData = [];
        $resultData[]   = $dataTitle;
        $defaultRow     =  $aEnd = 2;
        $isStart        =  true;
        foreach($data as $processKey=>$processVal)
        {
            $aStart                 = $isStart ? $defaultRow : $aEnd+1;
            $aEnd                   = $isStart ? $defaultRow : $aStart;
            $isStart                = false;
            $cDefault               = true;

            $processTitle           = $processVal['title'];
            if(isset($processVal['data'])){
                $fieldData              = $processVal['data'];
                foreach($fieldData as $fieldKey=>$fieldVal)
                {
                    $cStart             = $cDefault ? $aStart : $cEnd+1;
                    $cEnd               = $cDefault ? $aStart : $cStart;
                    $cDefault           = false;
                    $dDefault           = true;


                    $fieldTitle         = $fieldVal['title'];
                    $mustName           = $fieldVal['must_name'];
                    $fieldTitle         .= '('.$mustName.')';
                    $fieldTypeName      = $fieldVal['field_type_name'];
                    $selectData         = $fieldVal['data'];
                    if( $selectData ){
                        foreach($selectData as $selectKey=>$selectVal)
                        {
                            $dStart                 = $dDefault ? $cStart : $dEnd+1;
                            $dEnd                   = $dDefault ? $cStart : $dStart;
                            $dDefault               = false;

                            $selectTitle            = $selectVal['title'];
                            if(isset($selectVal['data']) && !empty($selectVal['data']))
                            {
                                $sonData            = $selectVal['data'];
                                foreach($sonData as $key=>$val)
                                {
                                    $sonTitle       = $val['title'];
                                    $temp           = [$processTitle,$fieldTitle,$fieldTypeName,$selectTitle,$sonTitle];
                                    $resultData[]   = $temp;
                                }
                                $sonDataCount       = count($sonData);
                                if($sonDataCount>1)
                                {
                                    $aEnd               = $aEnd + $sonDataCount - 1;
                                    $cEnd               = $cEnd + $sonDataCount - 1;
                                    $dEnd               = $dEnd + $sonDataCount - 1;
                                    $cellStr            = 'D'.$dStart.':D'.$dEnd;
                                    $cellData[]         = $cellStr;
                                }
                            } else {
                                $temp               = [$processTitle,$fieldTitle,$fieldTypeName,$selectTitle,''];
                                $resultData[]       = $temp;
                            }
                        }
                        $selectDataCount        = count($selectData);
                        if($selectDataCount>1)
                        {
                            $aEnd                   = $aEnd + $selectDataCount - 1;
                            $cEnd                   = $cEnd + $selectDataCount - 1;
                            $cellStr                = 'C'.$cStart.':C'.$cEnd;
                            $cellData[]             = $cellStr;
                            $cellStr                = 'B'.$cStart.':B'.$cEnd;
                            $cellData[]             = $cellStr;
                        }
                    } else {
                        $temp                   = [$processTitle,$fieldTitle,$fieldTypeName,'',''];
                        $resultData[]           = $temp;
                    }
                }
                $fieldDataCount         = count($fieldData);
                $aEnd                   = $aEnd + $fieldDataCount - 1;
                $cellStr                = 'A'.$aStart.':A'.$aEnd;
                $cellData[]             = $cellStr;
            }else {
                $temp                   = [$processTitle,'','','',''];
                $resultData[]           = $temp;
                $cellStr                = 'A'.$aStart.':A'.$aEnd;
                $cellData[]             = $cellStr;
                $aStart                 = $aStart + 1;
            }
        }
        $result     = ['data'=>$resultData,'cell'=>$cellData];
        return $result;
    }
    public function exportExcel($data)
    {
        $exportData     = isset($data['data']) ? $data['data'] : [];
        $cellData       = isset($data['cell']) ? $data['cell'] : [];
        \Excel::create('工序列表导出', function($excel) use($exportData,$cellData) {
            $excel->sheet('Sheetname', function($sheet) use($exportData,$cellData) {
                $sheet->freezeFirstRow();
                $sheet->setAutoSize(true);
                $sheet->fromArray($exportData, null, 'A1', false, false);
                foreach($cellData as $val)
                {
                    $sheet->mergeCells($val);
                    $sheet->cells($val, function($cells) {
                        $cells->setAlignment('center');
                        $cells->setValignment('center');
                    });
                }
            });
        })->export('xls');

    }
}